package com.example.advice;

import com.example.domain.Result;
import com.example.domain.ResultEnum;
import com.example.exception.BusinessException;
import com.example.exception.ForbiddenException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice(basePackages = "com.example")
public class ExceptionAdvice {

    @ExceptionHandler({BusinessException.class})
    public Result<?> handleBusinessException(BusinessException ex){
        return Result.failed(ex.getMessage());
    }

    @ExceptionHandler({ForbiddenException.class})
    public Result<?> handleForbiddenException(ForbiddenException ex){
        return Result.failed(ex.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder("校验失败");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
           stringBuilder.append(fieldError.getField()).append("：")
                   .append(fieldError.getDefaultMessage())
                   .append(",");
        }
        String msg = stringBuilder.toString();
        if (StringUtils.hasText(msg)) {
            return Result.failed(ResultEnum.VALIDATE_FAILED.getCode(), msg);
        }
        return Result.failed(ResultEnum.VALIDATE_FAILED);
    }


    @ExceptionHandler({ConstraintViolationException.class})
    public Result<?> handleConstraintViolationException(ConstraintViolationException ex){
        String msg = ex.getMessage();
        if (StringUtils.hasText(msg)) {
            return Result.failed(ResultEnum.VALIDATE_FAILED.getCode(), msg);
        }
        return Result.failed(ResultEnum.VALIDATE_FAILED);
    }
}
